﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;

using Entities;
using BLL;

namespace Stationery.UC
{
    public partial class UC_CookAddUpdate : System.Web.UI.UserControl
    {
        BLL_Cook bll_Cook = new BLL_Cook();        
        Entities.Cook obj_Cook = null;
        Entities.User obj_User = null;
        string vCook_id = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            obj_User = (Entities.User)Session[Utils.SESSION_LOGIN];
            if (obj_User == null)
            {
                Response.Redirect(UtilsURL.home);
            }
            if (Request.Params["status"] != null)
            {
                string strStatus = Request.Params["status"].ToString();
                ViewState["STATUS"] = strStatus;
                
                //Load Infor Cooking
                if (strStatus == "edit")
                {
                    vCook_id = Request.Params["cookid"].ToString();
                    if (vCook_id != null)
                    {
                        LoadCookById(Convert.ToInt32(vCook_id));
                    }
                    else
                    {
                        Response.Redirect(UtilsURL.news_list);
                    }
                }
            }
        }

        #region Load Data

        private void LoadCookById(int cook_id)
        {
            DataTable dt = new DataTable();
            dt = bll_Cook.Get_Cook_ByID(cook_id);            

            if (dt == null)
            {
                //ko lam gi
            }
            else
            {
                if (dt.Rows.Count <= 0)
                {
                    Session["dataCook"] = null;
                    Response.Redirect(UtilsURL.cook_list);
                }
                else
                {
                    DataRow dtr = dt.Rows[0];
                    
                    ASPxTextBoxTitle.Text = dtr["Title"].ToString();
                    ASPxHtmlEditorCookDesc.Html = dtr["Content_desc"].ToString();
                    ASPxHtmlEditorCookDetail.Html = dtr["Content_detail"].ToString();

                    if (dtr["Image_data"] != DBNull.Value)
                    {
                        byte[] blob = (byte[])dtr["Image_data"];
                        ASPxBinaryImageData.ContentBytes = blob;
                    }
                    else
                        ASPxBinaryImageData.ContentBytes = null;
                }
            }
        }

        private byte[] BmpToBytes(System.Drawing.Image bmp)
        {
            MemoryStream ms = null;
            byte[] bmpBytes = null;
            try
            {
                ms = new MemoryStream();
                // Save to memory using the Jpeg format
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                // read to end
                bmpBytes = ms.GetBuffer();
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                bmp.Dispose();
                if (ms != null)
                {
                    ms.Close();
                }
            }
            return bmpBytes;
        }

        #endregion

        #region Event Click
        protected void ASPxButtonAccept_Click(object sender, EventArgs e)
        {
            obj_Cook = new Entities.Cook();
            Int32 insert_id = 0;
            bool update = false;

            string imgContentType = "";

            if (Request.Params["status"] != null)
            {
                string strStatus = (string)ViewState["STATUS"];

                obj_Cook.TITLE = ASPxTextBoxTitle.Text.Trim();
                obj_Cook.CONTENT_DESC = ASPxHtmlEditorCookDesc.Html.ToString();
                obj_Cook.CONTENT_DETAIL = ASPxHtmlEditorCookDetail.Html.ToString();

                if (strStatus == "edit")
                {
                    if (Request.Params["cookid"] != null)
                    {
                        int cook_id = Convert.ToInt32(Request.Params["cookid"].ToString());
                        obj_Cook.COOK_ID = cook_id;
                                              
                        //Xu ly image
                        if (ASPxUploadControlImage.FileName == "")
                        {
                            //ko cap nhat Image                            
                            update = bll_Cook.UpdateCookNotImage(obj_Cook);
                        }
                        else
                        {
                            imgContentType = ASPxUploadControlImage.PostedFile.ContentType;
                            if (imgContentType.ToLower().StartsWith("image"))
                            {
                                //get the image from upload stream
                                System.Drawing.Bitmap b = (
                                    System.Drawing.Bitmap)System.Drawing.Image.FromStream(
                                    ASPxUploadControlImage.PostedFile.InputStream);
                                obj_Cook.IMAGE_DATA = BmpToBytes(b);

                                update = bll_Cook.UpdateCook(obj_Cook);
                            }
                            else
                            {
                                ASPxLabelException.Text = "Không là file Image";
                            }
                        }
                        //end Xu ly Image

                        if (update)
                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", String.Format("alert('Thành công!');location.href='Admin.aspx?id=cook'", UtilsURL.cook_list), true);
                        else
                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", String.Format("alert('KHÔNG Thành công!');location.href='Admin.aspx?id=cook'", UtilsURL.cook_list), true);
                    }
                }
                else if (strStatus == "add")
                {
                    ASPxBinaryImageData.Visible = false;                    
                    imgContentType = ASPxUploadControlImage.PostedFile.ContentType;

                    if (imgContentType.ToLower().StartsWith("image"))
                    {
                        //get the image from upload stream
                        System.Drawing.Bitmap b = (
                            System.Drawing.Bitmap)System.Drawing.Image.FromStream(
                            ASPxUploadControlImage.PostedFile.InputStream);
                        obj_Cook.IMAGE_DATA = BmpToBytes(b);
                    }
                    else
                    {
                        ASPxLabelException.Text = "Không là file Image";
                    }

                    insert_id = bll_Cook.InsertCook(obj_Cook);
                    if (insert_id > 0)
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", String.Format("alert('Thành công!');location.href='Admin.aspx?id=cook&status=add'", UtilsURL.cook_add), true);
                    }
                    else
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", String.Format("alert('KHÔNG Thành công!');location.href='Admin.aspx?id=cook&status=add'", UtilsURL.cook_add), true);
                }

                Session["dataCook"] = null;
            }
        }

        protected void ASPxButtonCancel_Click(object sender, EventArgs e)
        {
            Session["dataCook"] = null;
            Response.Redirect(UtilsURL.cook_list);
        }
        #endregion
    }
}